<template>
  <div class="flexContent">
    <h3>随货单信息</h3>
    <div class="inner">
      <el-form ref="ruleForm" :disabled="detail.isDetail" :model="sform" :rules="rules" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="仓库名称：" prop="warehouseId">
              <el-select v-model="sform.warehouseId" placeholder="请选择仓库" @change="changeWarehouse" filterable
                popper-class="eloption" style="width:70%;" @click.native="reqWarehouseList">
                <el-option v-for="item in warehouseList" :key="item.id" :value="item.id" :label="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="点采金额：" prop="commodityAmount">
              {{ sform.commodityAmount }} 元
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店名称:" prop="storeId">
              <el-select v-model="sform.storeId" style="width:70%;" popper-class="eloption" placeholder="请选择门店"
                filterable @change="setStoreAddress" @click.native="getShopEasy">
                <el-option v-for="shop in shopLists" :key="shop.id" :value="shop.id" :label="shop.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="备注：">
              <el-input v-clearEmoji v-model="sform.remark" placeholder="最多输入50个字符" maxlength="50" show-word-limit
                style="width:70%;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店地址：">
              <!-- <el-input v-clearEmoji v-model="sform.storeAddress" disabled style="width:70%;" /> -->
              {{ sform.storeAddress }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="add">
      <el-button class="addBtn" v-show="!detail.isDetail" @click="submitForm('ruleForm')">调要货单</el-button>
    </div>
    <div class="table">
      <el-form ref="formData" :model="formData">
        <el-table border class="tablebox" :data="formData.tableData" max-height="500" style="width: 100%" size="medium">
          <el-table-column align="center" type="index" label="序号" width="80" />
          <el-table-column align="center" prop="commodityName" label="商品名称" />
          <el-table-column align="center" prop="standard" label="规格" />
          <el-table-column align="center" prop="unitName" label="单位" />
          <el-table-column align="center" prop="commodityProducer" label="产地" />
          <el-table-column align="center" prop="manufactureTime" label="生产日期">
            <template slot-scope="{row}">
              <div>
                {{ row.manufactureTime | parseTime("YYYY-MM-DD") }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="batchNumber" label="批次号" />
          <el-table-column align="center" prop="deliveryNorms" label="配送规格" />
          <el-table-column align="center" prop="procureCount" label="随货数量">
            <template slot-scope="scope">
              <el-form-item v-if="!detail.isDetail && sform.creditCode != 'XIANSHANGMENDIAN'"
                :prop="'tableData.' + scope.$index + '.procureCount'" :rules="tableRules.procureCount">
                <el-input v-clearEmoji v-model.number="scope.row.procureCount" placeholder="" class="group-inp"
                  size="small" style="width: 100%;" @change="numberChange($event, scope.$index, scope.row)" />
                <!-- <span v-if="detail.isDetail">{{ scope.row.takeCount }}</span> -->
              </el-form-item>
              <span v-if="detail.isDetail || sform.creditCode == 'XIANSHANGMENDIAN'">{{ scope.row.procureCount }}</span>
            </template>
            <!-- <template slot-scope="scope" /> -->
          </el-table-column>
          <el-table-column align="center" prop="procureNumber" label="件数" />
          <el-table-column v-if="!detail.isDetail && sform.creditCode != 'XIANSHANGMENDIAN'" align="center" fixed="right"
            label="操作" width="200">

            <template slot-scope="scope">
              <el-button type="text" style="color: red;" @click="delRegionByIndex(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <div class="returnBtn">
      <el-button class="celBtn" v-if="!detail.isDetail" @click="cancelBtn">取消</el-button>
      <el-button class="celBtn" v-if="detail.isDetail" @click="cancelBtn">返回</el-button>
      <el-button class="addBtn" v-if="!detail.isDetail" @click="submitData('formData')">确定</el-button>
    </div>
    <el-dialog title="调要货单" :visible.sync="dialogTableVisible">
      <h3>调要货单</h3>
      <el-table border :data="gridData1" class="tablebox" height="202px" @current-change="showRow" size="medium">
        <el-table-column label="序号" width="80" align="center">
          <template scope="scope">
             <el-radio v-model="radio" class="radio" :label="scope.$index" @change="showRow(scope.row)"><span>{{
               scope.$index + 1 }}</span></el-radio>
          </template>
        </el-table-column>
        <el-table-column property="requireNumber" align="center" label="要货单编号" />
        <el-table-column property="createTime" align="center" label="分录时间">

          <template v-slot="{ row }">
            <span>{{ row.createTime | parseTime }}</span>
          </template>
        </el-table-column>
      </el-table>
      <h3 style="padding-top: 30px;">订单明细</h3>
      <el-table border :data="gridData2" class="tablebox" height="202px" size="medium">
        <el-table-column type="index" align="center" label="序号" width="80" />
        <el-table-column property="commodityName" align="center" label="商品名称" />
        <el-table-column property="commodityStandard" align="center" label="规格" />
        <el-table-column property="commodityUnit" align="center" label="单位" />
        <el-table-column property="commodityProducer" align="center" label="产地" />
        <el-table-column property="procureCount" align="center" label="拣货数量" />
        <el-table-column property="commodityBrand" align="center" label="品牌" />
      </el-table>
      <div slot="footer">
        <el-button class="celBtn" @click="cancelFn">取 消</el-button>
        <el-button class="addBtn" @click="confirmFn">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { DecimalUtils } from "@/utils/math";
import { printFollow, checkPrinter } from "@/utils/printLODOP"
import { reqWarehouseList } from '@/api/warehouse'
import { getShopEasy } from '@/api/shop'
import { reqFollowManifest, reqAddFollowOrder, reqChooseOrder } from "@/api/followManifest"
export default {
  name: 'PrintFollowManifest',
  data() {
    return {
      dialogTableVisible: false,
      sform: {
        warehouseId: '',
        storeId: '',
        storeAddress: '',
        remark: '', // 备注
        creditCode: '',
        commodityAmount: 0, // 点采金额
      },
      requireId: '', // 要货单ID
      requireNumber: '', // 要货单编号
      rules: {
        warehouseId: [
          { required: true, message: '请选择仓库', trigger: 'change' }
        ],
        storeId: [
          { required: true, message: '请选择门店', trigger: 'change' }
        ],
      },
      formData: {
        tableData: []
      },
      tableRules: {
        procureCount: [
          { required: true, message: '随货数不能为空' },
          // { type: 'number', message: '收货件数必须为数字' },
          { pattern: /^\+?[1-9]\d*$/, message: '随货数必须为正整数', trigger: 'blur' }
        ],
      },
      warehouseList: [],
      shopLists: [],

      idList: [],
      gridData1: [],
      gridData2: [],// 弹窗下方的表格数据
      gridId: "",
      selected: {},
      radio: '',
      detail: {
        isDetail: false,
        id: ''
      },
      printObj: {}
    }
  },
  created() {
    // this.reqWarehouseList();
    // this.getShopEasy()
    this.detail.id = this.$route.query.id
    this.detail.isDetail = !!this.$route.query.id
  },
  methods: {
    // 获取仓库列表
    async reqWarehouseList() {
      const res = await reqWarehouseList()
      if (res.code === 200) {
        this.warehouseList = res.data

      }
    },
    // 获取门店列表
    async getShopEasy() {
      const res = await getShopEasy()
      if (res.code === 200) {
        this.shopLists = res.data.store

      }
    },
    // 设置门店地址
    setStoreAddress(e) {
      let store = this.shopLists.find(item => item.id === e);
      console.log(e, store)
      this.sform.storeAddress = store.address;
      this.sform.creditCode = store.creditCode;
      this.formData.tableData = []
    },
    changeWarehouse() {
      this.formData.tableData = []
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.gridId = '';
          this.selected = {}
          this.radio = ''
          let { warehouseId, storeId } = this.sform;
          const res = await reqFollowManifest({ warehouseId, storeId, isFollow: '0' })
          if (res.code === 200) {
            this.gridData1 = res.data

          }
          this.idList = [];
          this.dialogTableVisible = true
        } else {
          return false
        }
      })
    },
    submitData(formName) {
      // let hasPrinter = checkPrinter();
      // if (!checkPrinter())
      //   return;
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.formData.tableData.length <= 0) return this.$message.warning('请先选择要货单')
          this.$refs.formData.validate(async (valid) => {
            if (valid) {
              let { warehouseId, storeId, remark, commodityAmount } = this.sform;
              let { requireNumber, requireId, idList } = this;
              let storeFollowList = this.formData.tableData;
              let reqObj = { warehouseId, storeId, remark, commodityAmount, requireNumber, requireId, storeFollowList, idList }
              let sum = 0;
              for (let i = 0; i < storeFollowList.length; i++) {
                let item = storeFollowList[i];
                sum = storeFollowList.reduce((su, pre) => {
                  if (pre.commodityId === item.commodityId) {
                    return su + +pre.procureCount;
                  } else {
                    return su;
                  }
                }, 0)


                item.totalNumber = sum / item.deliveryNorms;
                // if (sum % item.deliveryNorms !== 0) {
                //   item.totalNumber = 0;
                //   this.$message.warning("商品" + item.commodityName + "的随货数量总和须为配送规格的倍数")
                //   return ;
                // } else {
                //   item.totalNumber = sum / item.deliveryNorms;
                // }
              }
              console.log(reqObj);
              // return ;
              let hasPrinter = checkPrinter();
              const res = await reqAddFollowOrder(reqObj);
              if (res.code === 200) {
                this.printObj = res.data
                if (hasPrinter) {
                  printFollow(this.printObj)
                }
                console.log(res.data, '成功')
                this.$message.success('随货单正在打印')
                this.closeTag('receiving')
              } else if (res.code === 500) {
                // this.$message.error(res.message)
              } else {
                // this.$message.error(res.message)
              }
            }
          })
        }
      })
    },
    // 删除功能
    delRegionByIndex(index) {
      this.idList.push(this.formData.tableData[index].id);
      this.formData.tableData.splice(index, 1)
      this.sform.commodityAmount = 0;
      this.formData.tableData.forEach(item => {
        let ji = DecimalUtils.multiply(item.outboundPrice, item.procureCount);
        this.sform.commodityAmount = DecimalUtils.add(ji, this.sform.commodityAmount)
      })
      this.selected = {}
      this.radio = ''
    },
    // 弹窗的确定按钮
    async confirmFn() {
      if (this.gridId === '') {
        this.$message.warning('请先选择要货单')
        return;
      }
      this.formData.tableData = []
      this.sform.commodityAmount = 0;
      let res = await reqChooseOrder({ requireId: this.gridId })
      let dataArr = [];
      if (res.code === 200) {
        dataArr = res.data;
      }
      dataArr.forEach(item => {
        let ji = DecimalUtils.multiply(item.outboundPrice, item.procureCount);
        this.sform.commodityAmount = DecimalUtils.add(ji, this.sform.commodityAmount)
        this.formData.tableData.push({ ...item, procureCountCopy: item.procureCount });
      })
      this.gridData2 = []
      this.dialogTableVisible = false
    },
    cancelFn() {
      this.gridData2 = []
      this.dialogTableVisible = false
      this.selected = {}
      this.radio = ''
    },
    // 选择要货单逻辑
    showRow(row) {
      if (row == null) {
        return;
      }
      // 赋值给radio
      this.radio = this.gridData1.indexOf(row)
      this.selected = row
      this.gridData2 = row.storeRequireVoList
      this.gridId = row.id;
      this.requireNumber = row.requireNumber;
      this.requireId = row.id
    },
    // 随货数量验证
    numberChange(e, index, row) {
      this.sform.commodityAmount = 0;
      // 防止出现非法数字
      const procureCount = (row.procureCount + '').replace(/[^0-9.]/g, '');
      this.$set(this.formData.tableData[index], 'procureCount', procureCount)
      const procureCountCopy = row.procureCountCopy
      // 如果输入数据不合法强制修复输入数据
      if (procureCount > procureCountCopy) {
        this.$message.warning('随货数量不能大于拣货数量')
        this.$set(this.formData.tableData[index], 'procureCount', procureCountCopy)
      }

      // else if(procureCount%row.deliveryNorms!=0){
      //   this.$message.warning('随货数量须为配送规格的倍数')
      //   this.$set(this.formData.tableData[index], 'procureCount', procureCountCopy)
      // }

      // 计算总金额
      this.formData.tableData.forEach(item => {
        let ji = DecimalUtils.multiply(item.outboundPrice, item.procureCount);
        this.sform.commodityAmount = DecimalUtils.add(ji, this.sform.commodityAmount)
      })
      // 计算件数
      const procureNumber = row.procureCount / row.deliveryNorms;
      this.$set(this.formData.tableData[index], 'procureNumber', DecimalUtils.subNumber(procureNumber, 2));
    },

    // 返回按钮逻辑
    cancelBtn() {
      this.closeTag('receiving')
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 10px;

  .inner {
    padding: 15px;
    padding-top: 30px;
    background-color: #fff;
  }
}
</style>
